//
//  CIMSignalServiceBuffer.m
//  CIMSDK
//
//  Created by Chentao on 2022/9/3.
//

#import "CIMSignalServiceBuffer.h"

@interface CIMSignalServiceBuffer ()

@property (nonatomic, strong) NSMutableData *byteDatas;

@end

@implementation CIMSignalServiceBuffer

- (instancetype)init {
    self = [super init];

    if (self) {
        self.byteDatas = [[NSMutableData alloc] init];
    }

    return self;
}

- (void)appendData:(NSData *)data {
    [self.byteDatas appendData:data];

    BOOL hasPacket = YES;

    while (hasPacket) {
        @autoreleasepool {
            if (CIMSIGNAL_PACKET_HEAD_SIZE <= self.byteDatas.length) {
                NSData *headData = [self.byteDatas subdataWithRange:NSMakeRange(0, CIMSIGNAL_PACKET_HEAD_SIZE)];
                uint8_t *ptr = (uint8_t *)headData.bytes;
                uint64_t _poz = 0;

                uint8_t tag = *(uint8_t *)ptr;
                _poz += sizeof(uint8_t);

                uint16_t bodyLength = *(uint16_t *)(ptr + _poz);
                _poz += sizeof(uint16_t);

                UInt32 packetSize = CIMSIGNAL_PACKET_HEAD_SIZE + bodyLength;

                if (packetSize <= self.byteDatas.length) {
                    NSData *packetBody = [self.byteDatas subdataWithRange:NSMakeRange(CIMSIGNAL_PACKET_HEAD_SIZE, bodyLength)];

                    CIMSignalPacket *signalPacket = [[CIMSignalPacket alloc] init];
                    signalPacket.tag = tag;
                    signalPacket.bodyLength = bodyLength;
                    signalPacket.packetBody = packetBody;

                    if (self.delegate && [self.delegate respondsToSelector:@selector(signalServiceBuffer:receiveSignalPacket:)]) {
                        [self.delegate signalServiceBuffer:self receiveSignalPacket:signalPacket];
                    }

                    NSMutableData *newByteDatas = [self subdata:self.byteDatas loc:packetSize length:self.byteDatas.length - packetSize];
                    self.byteDatas = newByteDatas;
                    hasPacket = YES;
                } else {
                    hasPacket = NO;
                }
            } else {
                hasPacket = NO;
            }
        }
    }
}

- (void)clear {
    @autoreleasepool {
        self.byteDatas = [[NSMutableData alloc] init];
    }
}

- (NSMutableData *)subdata:(NSMutableData *)data loc:(NSUInteger)loc length:(NSUInteger)len {
    NSRange subRange = NSMakeRange(loc, len);
    NSMutableData *newByteDatas = [[NSMutableData alloc] initWithData:[data subdataWithRange:subRange]];

    return newByteDatas;
}

@end
